<?php	
	oh_module_header();
	
	// Interface function	
	function oh_module_xls($tokens) {		
		return oh_this();
	} 

	// Option file required
	require_once(dirname(__FILE__)."/Excel/reader.php");
	
	// Main class of module
	class oh_class_xls {
		public $data;
		public $file;

		function oh_class_xls() {
			$this->data = array();
		}
		function load($filename) {
			$data = new Spreadsheet_Excel_Reader();
			$data->setOutputEncoding('CP1251');
			$data->read($filename);

			$this->file = $filename;
			$this->data[$this->file] = $data;

			return oh_this();
		}
		function cell($cell,$value=null) {
			if ($value===null) {
				$cell = strtoupper(trim($cell));
				$cell = explode(":",$cell);
				if (count($cell)==1) {					
					$c = $this->parse($cell[0]);
					return $this->data[$this->file]->sheets[0]["cells"][$c["x"]][$c["y"]];
				} else {
					$c0 = $this->parse($cell[0]);
					$c1 = $this->parse($cell[1]);
					$oo = array();
					
					$cx = 0;				
					for ($x=(int)$c0['x'];$x<=(int)$c1['x'];$x++) {
						$cy = 0;					
						$oo[$cx] = array();
						for ($y=(int)$c0['y'];$y<=(int)$c1['y'];$y++) {
							$value = $this->data[$this->file]->sheets[0]["cells"][$x][$y];
							//$value = isset($value) ? $value : "";
							$oo[$cx][$cy] = $value;
							$cy++;
						}
						$cx++;
					}
					return $oo;
				}				
			} else {
				return oh_this();
			}
		}

		function showdata() {
			oh_dump(
				$this->data[$this->file]->sheets[0]["cells"]
			);
		}


		function info() {
			echo 'xls:module:info';
		}
		
		function parse($cell) {
			preg_match_all("/([A-Z]+)([0-9]+)/",$cell,$result);
			$x = $this->letter2number($result[1][0]);
			$y = (int)$result[2][0];
			$o = array("x"=>$x,"y"=>$y,"original"=>$cell);
			return $o;
		}
		function letter2number($s) {
			$s = strtoupper(trim($s));
			$t = 0;
			for($i=0;$i<strlen($s);$i++) {
				$v = (ord($s{$i})-64);
				$e = pow(26,(strlen($s)-$i-1));
				$t += $e * $v;
				//echo "V:$v E:$e <br>";
			}
			return $t;
		}
	}
	
	// Main object of module
	global $oh_object_xls;
	$oh_object_xls = new oh_class_xls();
?>
